package tsing.javase.thread.communication;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程间的通信 ：wait、notify、notifyAll等方法，
 */

class ComDemo{
    private  Integer flag =1;

    private Lock lock = new ReentrantLock();

    private Condition cA = lock.newCondition();
    private Condition cB = lock.newCondition();
    private Condition cC = lock.newCondition();

    public void printA(int n){
        lock.lock();
        try {
            //判断
            while(flag!=1){
                cA.await();
            }
            //干活
            for (int i = 0; i < 5; i++) {
                System.out.println("第"+i+"次\taa\t\t"+n +"轮");
            }
            flag = 2;  //先修标志位为2
            //通知
            cB.signal(); //通知B
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB(int n){
        lock.lock();
        try {
            while(flag!=2){
                cB.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println("第"+i+"次\tbb\t\t"+n +"轮");
            }
            flag=3;
            cC.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


    public void printC(int n){
        lock.lock();
        try {
            while(flag!=3){
                cC.await();
            }

            for (int i = 0; i < 15; i++) {
                System.out.println("第"+i+"次\tcc\t\t"+n +"轮");
            }
            flag=1;
            cA.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
